package com.cn.shuangzi.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Outline;
import android.graphics.Rect;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.cn.shuangzi.R;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.bean.MaterialsInfo;
import com.cn.shuangzi.bean.VipInfo;
import com.cn.shuangzi.common.SZConst;
import com.google.gson.Gson;

import org.apaches.commons.codec.digest.DigestUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cc.shinichi.library.ImagePreview;
import cc.shinichi.library.view.listener.OnBigImagePageChangeListener;
import cn.bingoogolapple.bgabanner.BGABanner;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by CN.
 */

public class SZUtil {
    public static void log(String msg) {
        if (SZManager.getInstance().isDebugMode()) {
            Log.v("CN", "=======================");
            Log.v("CN", msg);
            Log.v("CN", "=======================");
        }
    }

    public static void saveUToken(String token){
        new SZXmlUtil("um_token").put("um_token",token);
    }
    public static String getUToken(){
        return new SZXmlUtil("um_token").getString("um_token");
    }
    public static void setMaterialsBanner(final Context context, BGABanner banner, List<MaterialsInfo> bannerList,
                                          final BGABanner.Delegate<RelativeLayout, MaterialsInfo> bannerClickListener) {
        setMaterialsBanner(context, banner, bannerList, null, bannerClickListener);
    }

    public static void setMaterialsBanner(final Context context, BGABanner banner, List<MaterialsInfo> bannerList, final SZImageLoader imageLoader,
                                          final BGABanner.Delegate<RelativeLayout, MaterialsInfo> bannerClickListener) {
        setMaterialsBanner(context,banner,bannerList,imageLoader,bannerClickListener,null);
    }

    public static void setMaterialsBanner(final Context context, BGABanner banner, List<MaterialsInfo> bannerList, final SZImageLoader imageLoader,
                                          final BGABanner.Delegate<RelativeLayout, MaterialsInfo> bannerClickListener, BGABanner.Adapter<RelativeLayout, MaterialsInfo> bannerAdp) {
        if (SZValidatorUtil.isValidList(bannerList)) {
            final SZImageLoader szImageLoader;
            if (imageLoader == null) {
                szImageLoader = new SZImageLoader(context);
            } else {
                szImageLoader = imageLoader;
            }
            banner.setData(R.layout.item_banner, bannerList, null);
            banner.setDelegate(new BGABanner.Delegate<RelativeLayout, MaterialsInfo>() {
                @Override
                public void onBannerItemClick(BGABanner banner, RelativeLayout itemView, MaterialsInfo model, int position) {
                    if (MaterialsInfo.ACTION_APP_STORE.equalsIgnoreCase(model.getAction())) {
                        model.launchApp(context);
                    }
                    if (bannerClickListener != null) {
                        bannerClickListener.onBannerItemClick(banner, itemView, model, position);
                    }
                }
            });
            if (bannerAdp == null) {
                banner.setAdapter(new BGABanner.Adapter<RelativeLayout, MaterialsInfo>() {
                    @Override
                    public void fillBannerItem(BGABanner banner, RelativeLayout itemView, MaterialsInfo materialsInfo, int position) {
                        ImageView imgGoods = itemView.findViewById(R.id.imgBanner);
                        szImageLoader.load(imgGoods, materialsInfo.getImage());
                    }
                });
            } else {
                banner.setAdapter(bannerAdp);
            }
        }
    }

    public static void clipViewCorner(View view, final int pixel) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            view.setClipToOutline(true);
            view.setOutlineProvider(new ViewOutlineProvider() {
                @Override
                public void getOutline(View view, Outline outline) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), pixel);
                    }
                }
            });
        }
    }

    public static String getPhoneNumbers(String text) {
        String regex = "1[23456789]\\d{9}";//正则表达式
        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    public static boolean isUsedApp() {
        return new SZXmlUtil("isUsedApp").getBoolean("isUsedApp", false);
    }

    public static void setUsedApp() {
        new SZXmlUtil("isUsedApp").put("isUsedApp", true);
    }

    public static boolean isFirstLoad(String key) {
        if (key == null) {
            key = SZConst.FIRST_LOAD_1;
        }
        return !SZValidatorUtil.isValidString(new SZXmlUtil(SZManager.getInstance().getContext(), SZConst.SETTING).getString(key));
    }

    public static void setFirstLoaded(String key) {
        if (key == null) {
            key = SZConst.FIRST_LOAD_1;
        }
        new SZXmlUtil(SZManager.getInstance().getContext(), SZConst.SETTING).put(key, SZConst.NO);
    }

    public static void showBigImg(Activity activity, String url, ImagePreview.LoadStrategy loadStrategy) {
        ImagePreview.getInstance()
                .setContext(activity)
                .setIndex(0)
                .setImage(url)
                .setLoadStrategy(loadStrategy == null ? ImagePreview.LoadStrategy.AlwaysOrigin : loadStrategy)
                .setZoomTransitionDuration(300)
                .setShowErrorToast(false)
                .setEnableClickClose(true)
                .setEnableDragClose(true)
                .setEnableUpDragClose(true)
                .setShowCloseButton(false)
                .setShowDownButton(true)
                .setDownIconResId(R.mipmap.ic_download_dark)
                .setFolderName(SZFileUtil.getInstance().getDownloadPathName())
                .setShowIndicator(true)
                .setErrorPlaceHolder(R.drawable.load_failed).start();
    }

    public static void showBigImg(Activity activity, int index, List<String> imageList, OnBigImagePageChangeListener onBigImagePageChangeListener, ImagePreview.LoadStrategy loadStrategy) {
        ImagePreview.getInstance()
                .setContext(activity)
                .setIndex(index)
                .setImageList(imageList)
                .setLoadStrategy(loadStrategy == null ? ImagePreview.LoadStrategy.AlwaysOrigin : loadStrategy)
                .setFolderName(SZFileUtil.getInstance().getDownloadPathName())
                .setZoomTransitionDuration(300)
                .setBigImagePageChangeListener(onBigImagePageChangeListener)
                .setShowErrorToast(false)
                .setEnableClickClose(true)
                .setEnableDragClose(true)
                .setEnableUpDragClose(true)
                .setShowCloseButton(false)
                .setShowDownButton(true)
                .setDownIconResId(R.mipmap.ic_download_dark)
                .setShowIndicator(true)
                .setErrorPlaceHolder(R.drawable.load_failed).start();
    }

    public static String getUserCenterAvatarUrl(String objName) {
        if (SZValidatorUtil.isValidString(objName)) {
            return "https://center.cdn.xiangmaikeji.com/" + objName;
        }
        return null;
    }

    public static Map<String, String> getErrorEventMap(String platform, String errorCode, String errorMsg) {
        return getErrorEventMap(platform, null, errorCode, errorMsg);
    }

    public static Map<String, String> getErrorEventMap(String platform, String errorId, String errorCode, String errorMsg) {
        Map<String, String> params = new HashMap<>();
        try {
            JSONObject jsonObject = new JSONObject();
            if (errorId != null) {
                jsonObject.put(SZConst.ERROR_ID, errorId);
            }
            jsonObject.put(SZConst.ERROR_MSG, errorMsg);
            jsonObject.put(SZConst.ERROR_CODE, errorCode);
            params.put(platform, jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return params;
    }

    @NonNull
    public static String md5(String content) {
        return DigestUtils.md2Hex(content);
    }

    @NonNull
    public static String sha1(String content) {
        return DigestUtils.sha1Hex(content);
    }

    public static String makeSign(String appId, String appKey, long currentTime) {
        String sha1 = DigestUtils.sha1Hex(appKey + currentTime + appKey);
        String md5 = DigestUtils.md5Hex(sha1 + appId);
        return md5;
    }

    public static void hideSoftInput(Activity activity, View view) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }

    // 調用系統方法分享文件
    public static void shareFile(Context context, File file) {
        if (null != file && file.exists()) {
            Intent share = new Intent(Intent.ACTION_SEND);
            share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            share.setType(getMimeType(file.getAbsolutePath()));//此处可发送多种文件
            share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(Intent.createChooser(share, "分享"));
        } else {
            SZToast.error("分享文件不存在");
        }
    }

    public static MultipartBody.Part prepareFilePart(String partName, String path) {
        File file = new File(path);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse(getMimeType(path)), file);
        return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
    }

    public static String getMimeType(String filePath) {
        try {
            String ext = MimeTypeMap.getFileExtensionFromUrl(filePath);
            return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "*/*";
    }


    public static Bitmap getBitmapFromView(View view) {
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap screenShotBm = view.getDrawingCache();
        Bitmap bitmapNew = duplicateBitmap(screenShotBm);
        try {
            screenShotBm.recycle();
        } catch (Exception e) {
            e.printStackTrace();
        }
        view.setDrawingCacheEnabled(false);
        view.destroyDrawingCache();//注意,这里需要释放缓存
        return bitmapNew;
    }

    public static Bitmap duplicateBitmap(Bitmap bmpSrc) {
        if (null == bmpSrc) {
            return null;
        }
        int bmpSrcWidth = bmpSrc.getWidth();
        int bmpSrcHeight = bmpSrc.getHeight();
        Bitmap bmpDest = Bitmap.createBitmap(bmpSrcWidth, bmpSrcHeight, Bitmap.Config.ARGB_8888);
        if (null != bmpDest) {
            Canvas canvas = new Canvas(bmpDest);
            final Rect rect = new Rect(0, 0, bmpSrcWidth, bmpSrcHeight);
            canvas.drawBitmap(bmpSrc, rect, rect, null);
        }
        return bmpDest;
    }

    public static boolean saveTmpImg(Bitmap bitmap) {
        try {
            File mFile = SZFileUtil.getInstance().getOneTmpPic();                        //将要保存的图片文件
            FileOutputStream outputStream = new FileOutputStream(mFile);     //构建输出流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);  //compress到输出outputStream
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static HashMap<String, String> json2HashMap(String json) {
        HashMap<String, String> data = new HashMap<String, String>();
        // 将json字符串转换成jsonObject
        try {
            JSONObject jsonObject = new JSONObject(json);
            Iterator it = jsonObject.keys();
            // 遍历jsonObject数据，添加到Map对象
            while (it.hasNext()) {
                String key = String.valueOf(it.next());
                String value = jsonObject.get(key) == null ? "" : jsonObject.getString(key);
                data.put(key, value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return data;
    }

    /**
     * ******************
     * 获取版本号(内部识别号)
     *
     * @return ******************
     */
    public static int getVersionCode() {
        try {
            PackageInfo pi = SZManager.getInstance().getContext().getPackageManager()
                    .getPackageInfo(SZApp.getInstance().getPackageName(), 0);
            return pi.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * ******************
     * 获取版本名称
     */
    public static String getVersionName() {
        try {
            PackageInfo pi = SZApp.getInstance().getPackageManager()
                    .getPackageInfo(SZApp.getInstance().getPackageName(), 0);
            return pi.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    // 字符串截断
    public static String getLimitString(String source, int length) {
        if (null == source) {
            return "";
        } else if (source.length() > length) {
            return source.substring(0, length).replace('\n', ' ') + "...";
        } else {
            return source.replace('\n', ' ');
        }
    }

    public static <T extends View> T findViewById(View view, int id) {
        if (view != null && id > 0) {
            return (T) view.findViewById(id);
        }
        return null;
    }

    /**
     * 时间格式化
     */
    public static String getHMSTime(long seconds) {
        String formatTime;
        String hs, ms, ss;

        long h, m, s;
        h = seconds / 3600;
        m = (seconds % 3600) / 60;
        s = (seconds % 3600) % 60;
        if (h < 10) {
            hs = "0" + h;
        } else {
            hs = "" + h;
        }

        if (m < 10) {
            ms = "0" + m;
        } else {
            ms = "" + m;
        }

        if (s < 10) {
            ss = "0" + s;
        } else {
            ss = "" + s;
        }
        if (hs.equals("00")) {
            formatTime = ms + ":" + ss;
        } else {
            formatTime = hs + ":" + ms + ":" + ss;
        }
        return formatTime;
    }

    /**
     * 时间格式化
     */
    public static String getFullHMSTime(long seconds) {
        String formatTime;
        String hs, ms, ss;

        long h, m, s;
        h = seconds / 3600;
        m = (seconds % 3600) / 60;
        s = (seconds % 3600) % 60;
        if (h < 10) {
            hs = "0" + h;
        } else {
            hs = "" + h;
        }

        if (m < 10) {
            ms = "0" + m;
        } else {
            ms = "" + m;
        }

        if (s < 10) {
            ss = "0" + s;
        } else {
            ss = "" + s;
        }
        formatTime = hs + ":" + ms + ":" + ss;
        return formatTime;
    }

    /**
     * *******************
     * bitmap转byte数组
     *
     * @param bmp
     * @param needRecycle
     * @return *******************
     */
    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


    /**
     * 获取裁剪图片Intent
     *
     * @param imgSrcUri  需要裁剪图片的uri
     * @param imgDestUri 裁剪后存储图片的uri
     * @param outputX
     * @param outputY
     */
    public static Intent getCropImageIntent(Uri imgSrcUri, Uri imgDestUri, int outputX, int outputY) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imgSrcUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imgDestUri); // no face detection
        return intent;
    }

    public static Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(SZManager.getInstance().getContext().getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /****************
     *
     * 一键加群
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回false表示呼起失败
     ******************/
    public static boolean joinQQGroup(Activity activity, String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            activity.startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }

    /**
     * 根据apk文件判断该apk是否已经安装
     *
     * @return
     */
    public static boolean isAppInstalled(String appPackageName) {
        if (appPackageName == null) {
            return false;
        }
        return getAppNameByPackageName(appPackageName) == null ? false : true;
    }

    /**
     * ******************
     * 安装apk
     *
     * @param file ******************
     */
    public static boolean installApk(File file) {
        if (SZApp.getInstance() == null)
            return false;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // 由于没有在Activity环境下启动Activity,设置下面的标签
                //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                SZUtil.log("packageInstall:" + SZApp.getInstance().getPackageName());
                Uri apkUri = FileProvider.getUriForFile(SZApp.getInstance(), SZApp.getInstance().getPackageName() +
                                ".fileprovider",
                        file);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android" +
                        ".package-archive");
            }
            if (SZApp.getInstance().getTopActivity() != null) {
                SZApp.getInstance().getTopActivity().startActivity(intent);
            } else {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                SZApp.getInstance().startActivity(intent);
            }
            SZUtil.log("启动安装");
            return true;
        } catch (Exception e) {
            SZUtil.log("installException:" + e.getMessage());
            return false;
        }
    }

    /**
     * 通过包名获取应用程序的名称。
     *
     * @param packageName 包名。
     * @return 返回包名所对应的应用程序的名称。
     */

    public static String getAppNameByPackageName(String packageName) {
        PackageManager pm = SZManager.getInstance().getContext().getPackageManager();
        String name = null;
        try {
            name = pm.getApplicationLabel(pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA)).toString();
        } catch (PackageManager.NameNotFoundException e) {
        }
        return name;
    }

    public static void launchAppStoreDetail(Context context, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg))
                return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            //如果设置了market包名 打开指定app市场
            if (!TextUtils.isEmpty(marketPkg))
                intent.setPackage(marketPkg);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

        return wm.getDefaultDisplay().getWidth();
    }

    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

        return wm.getDefaultDisplay().getHeight();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int dip2px(float dpValue) {
        final float scale = SZManager.getInstance().getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(float pxValue) {
        final float scale = SZManager.getInstance().getContext().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static String getSZ_APPID(Context context) {
        String appId = getAppMetaDataString(context, SZConst.SZ_APPID);
        if(appId!=null&&appId.contains("sz_")){
            appId = appId.replace("sz_","");
        }
        return appId;
    }

    public static String getTT_SPLASH_ID(Context context) {
        return String.valueOf(getAppMetaDataInt(context, "TT_SPLASH_ID"));
    }

    public static String getGDT_SPLASH_ID(Context context) {
        return getAppMetaDataString(context, "GDT_SPLASH_ID").substring(4);
    }

    public static String getTT_APPID(Context context) {
        return String.valueOf(getAppMetaDataInt(context, "TT_APPID"));
    }

    public static String getGDT_APPID(Context context) {
        return String.valueOf(getAppMetaDataInt(context, "GDT_APPID"));
    }

    public static String getChannel(Context context) {
        return getAppMetaDataString(context, "UMENG_CHANNEL");
    }

    public static String getAppMetaDataString(Context context, String name) {
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            return appInfo.metaData.getString(name);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static int getAppMetaDataInt(Context context, String name) {
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            return appInfo.metaData.getInt(name);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static long getAppMetaDataLong(Context context, String name) {
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            return appInfo.metaData.getLong(name);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static boolean isValidConnect(Context context) {
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
            //获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context
                    .CONNECTIVITY_SERVICE);
            //获取ConnectivityManager对象对应的NetworkInfo对象
            //获取WIFI连接的信息
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null) {
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    return networkInfo.isConnected();
                } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    return networkInfo.isConnected();
                }
            }
            return false;
            //API大于23时使用下面的方式进行网络监听
        } else {
            //获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context
                    .CONNECTIVITY_SERVICE);

            //获取所有网络连接的信息
            Network[] networks = connMgr.getAllNetworks();
            //通过循环将网络信息逐个取出来
            boolean isWifiConnected = false;
            for (int i = 0; i < networks.length; i++) {
                //获取ConnectivityManager对象对应的NetworkInfo对象
                NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
                if (networkInfo != null) {
                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        isWifiConnected = networkInfo.isConnected();
                        break;
                    } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        isWifiConnected = networkInfo.isConnected();
                        break;
                    }
                }
            }
            return isWifiConnected;
        }
    }

    public static int getVersionCode(Context context) {
        try {
            PackageInfo pi = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //获取应用设置界面Intent
    public static Intent getAppSettingIntent() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", SZApp.getInstance().getPackageName(), null);
        intent.setData(uri);
        return intent;
    }

    public static <T extends Object> T copyMode(Object json, Class<T> classT) {
        if (json != null) {
            Gson gson = new Gson();
            return new Gson().fromJson(gson.toJson(json), classT);
        }
        return null;
    }

    public static String getSearchBeginTimeExact(String date) {
        return date + " 00:00:00";
    }

    public static String getSearchEndTimeExact(String date) {
        return date + " 23:59:59";
    }

    /**
     * 启动第三方apk
     * <p>
     * 如果已经启动apk，则直接将apk从后台调到前台运行（类似home键之后再点击apk图标启动），如果未启动apk，则重新启动
     */
    public static boolean launchAPP(Context context, String packageName) {
        if (context == null) {
            return false;
        }
        Intent intent = getAppOpenIntentByPackageName(context, packageName);
        if (intent == null) {
            return false;
        }
        context.startActivity(intent);
        return true;
    }

    public static Intent getAppOpenIntentByPackageName(Context context, String packageName) {
        String mainAct = null;
        PackageManager pkgMag = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);

        @SuppressLint("WrongConstant") List<ResolveInfo> list = pkgMag.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(packageName)) {
                mainAct = info.activityInfo.name;
                break;
            }
        }
        if (TextUtils.isEmpty(mainAct)) {
            return null;
        }
        intent.setComponent(new ComponentName(packageName, mainAct));
        return intent;
    }

    public static Bitmap getBitmapWeChatShareThumbnail(Bitmap bitMap) {
        return getBitmapThumbnail(bitMap, 99, 99);
    }

    public static Bitmap getBitmapThumbnail(Bitmap bitMap, int widthNew, int heightNew) {
        if (bitMap == null) {
            return null;
        }
        int width = bitMap.getWidth();
        int height = bitMap.getHeight();
        // 设置想要的大小
        int newWidth = widthNew;
        int newHeight = heightNew;
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newBitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height, matrix, true);
        return newBitMap;
    }

    public static void startActivityFastFromBack(Context context, Class classTo) {
        Intent intent = new Intent(context, classTo);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent =
                PendingIntent.getActivity(context, 0, intent, 0);
        try {
            pendingIntent.send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    public static boolean isIgnoringBatteryOptimizations(Context context) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Activity.POWER_SERVICE);
        boolean hasIgnored = true;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            hasIgnored = powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
        }
        return hasIgnored;
    }

    public static void openIgnoringBatteryOptimizations(Context context) {
        Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        PackageManager packageManager = context.getPackageManager();
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        if (intent.resolveActivity(packageManager) != null) {
            context.startActivity(intent);
        }
    }

    public static boolean checkNotification(Context context) {
        return NotificationManagerCompat.from(context).areNotificationsEnabled();
    }

    public static void openAppDetailSetting(Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(intent);
    }

    public static boolean isOpenLocationService(Context context) {
        LocationManager lm = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    public static void openLocationServiceIntent(Activity context, int requestCode) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        context.startActivityForResult(intent, requestCode);
    }

    public static boolean isServiceRunning(Context context, Class<? extends Service> service) {
        if (service == null)
            return false;
        ActivityManager myManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(500);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString()
                    .equals(service.getName())) {
                return true;
            }
        }
        return false;
    }

    public static String getHidePhoneStr(String phone) {
        if (SZValidatorUtil.isValidString(phone)) {
            return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4, phone.length());
        }
        return "";
    }

    public static void copyClipboard(Context context, String content) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("Label", content);
        cm.setPrimaryClip(mClipData);
    }

    public static String getClipboard(Context context) {
        try {
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData data = cm.getPrimaryClip();
            ClipData.Item item = data.getItemAt(0);
            String content = item.getText().toString();
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
